/*
 * @(#)SmsManager.java
 * 2014-1-7 下午11:41:13
 * 
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.msg.service;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.utils.ExceptionUtils;
import com.qyxx.platform.inf.adapter.AdapterException;
import com.qyxx.platform.inf.adapter.NeiTask;
import com.qyxx.platform.sysmng.accountmng.dao.UserDao;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.msg.dao.SmsMsgDao;
import com.qyxx.platform.sysmng.msg.entity.SmsMsg;


/**
 *  短信服务类
 *  @author gxj
 *  @version 1.0 2014-1-7 下午11:41:13
 *  @since jdk1.6 
 */
@Component
@Transactional
public class SmsManager {
	
	private static Logger logger = LoggerFactory.getLogger(SmsManager.class);
	
	private static final String FIND_UNSEND_HQL = "select a from SmsMsg a where a.status = ? and (a.regSendTime is null or a.regSendTime <= ?)";
	
	private SmsMsgDao smsMsgDao;

	private User user;
	
	private UserDao userDao;
	
	/**
	 * @param userDao
	 */
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * @param smsMsgDao
	 */
	@Autowired
	public void setSmsMsgDao(SmsMsgDao smsMsgDao) {
		this.smsMsgDao = smsMsgDao;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	
	/**
	 * 分页查询数据列表
	 * 使用属性过滤条件查询日志
	 */
	@Transactional(readOnly = true)
	public Page<SmsMsg> queryList(final Page<SmsMsg> page, final List<PropertyFilter> filters) {
		return preHandlePage(smsMsgDao.findPage(page, filters));
	}

	/**
	 * 获取单条数据对象
	 * 
	 * @param id
	 * @return
	 */
	@Transactional(readOnly = true)
	public SmsMsg get(Long id) {
		return smsMsgDao.get(id);
	}
	
	/**
	 * 保存数据
	 * 
	 * @param entity
	 */
	public void save(SmsMsg entity) {
		Long id = entity.getId();
		if(id==null) {
			entity.setCreateUser(user.getId());
			entity.setCreateTime(new Date());
		} else {
			entity.setLastUpdateUser(user.getId());
			entity.setLastUpdateTime(new Date());
		}
		smsMsgDao.save(entity);
	}
	
	
	/**
	 * 更新状态
	 * 
	 * @param id
	 * @param status
	 */
	public void updateStatus(Long id, String status) {
		SmsMsg smm = smsMsgDao.get(id);
		smm.setStatus(status);
		smm.setLastUpdateTime(new Date());
		smm.setLastUpdateUser(user.getId());
		/*if(SmsMsg.STATUS_UNSEND.equals(status) && smm.getRegSendTime() == null) {
			//待发且非定时发送，则立即发送短信
			sendSms(smm);
		}*/
	}
	
	/**
	 * 批量删除数据
	 * 
	 * @param ids
	 */
	public void delete(Long[] ids) {
		if(null!=ids) {
			for(Long id : ids) {
				smsMsgDao.delete(id);
			}
		}
	}
	
	/**
	 * 发送单条短信
	 * 
	 * @param smm
	 */
	public void sendSms(SmsMsg smm) {
		String tp = smm.getTargetPhone();
		String content = smm.getSmsBody();
		try {
			smm.setSendTime(new Date());
			NeiTask task = SmsFactory.sendSms(tp, content, smm.getServiceSms());
			if(task.getIsReturnSuccess()) {
				smm.setStatus(SmsMsg.STATUS_SEND);
			}
			smm.setResult(task.getReport());
		} catch (AdapterException e) {
			logger.error("发送短信出现异常", e);
			smm.setResult(ExceptionUtils.getStackTrace(e));
		} finally {
			smsMsgDao.save(smm);
		}
	}
	
	/**
	 * 发送所有待发短信
	 */
	public void sendAllSms() {
		List<SmsMsg> smsList = smsMsgDao.find(FIND_UNSEND_HQL, SmsMsg.STATUS_UNSEND, new Date());
		if(smsList != null) {
			for(SmsMsg sms : smsList) {
				sendSms(sms);
			}
		}
	}
	
	/**
	 * 处理Page对象，翻译字段
	 * 
	 * @param page
	 * @return
	 */
	public Page<SmsMsg> preHandlePage(Page<SmsMsg> page) {
		List<SmsMsg> list = page.getResult();
		if(list != null) {
			for(SmsMsg n : list) {
				n.setCreateUserCaption(userDao.getUserNameById(n.getCreateUser()));
			}
		}
		return page;
	}
	
}
